package apptoko.com;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.event.Event.CheckUserBirthdayFailed;
import apptoko.com.event.Event.ConfirmUserBirthdayFailed;
import apptoko.com.event.Event.ConfirmUserBirthdaySucceed;
import apptoko.com.network.HttpHelper;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;

import apptoko.com.R;
import com.easy.facebook.android.apicall.GraphApi;
import com.easy.facebook.android.data.User;
import com.easy.facebook.android.error.EasyFacebookError;
import com.easy.facebook.android.facebook.FBLoginManager;
import com.easy.facebook.android.facebook.Facebook;
import com.easy.facebook.android.facebook.LoginListener;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.util.AsyncExecutor;
import de.greenrobot.event.util.AsyncExecutor.RunnableEx;

public class BirthdayDialogActivity extends Activity implements LoginListener {
	private ProgressDialog progressDialog;
	private String FB_APP_ID;
	private static final int FB_REQUEST_CODE = 69;
	private FBLoginManager fbLoginManager;
	private String fbAccount;
	private Handler handler;
	private int gold_tym;
	private BackgroundTasks bgTask;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_birthday_dialog);
		progressDialog=new ProgressDialog(this);
		progressDialog.setMessage(getResources().getString(R.string.loading));
		progressDialog.setCancelable(false);
		handler=new Handler();
		bgTask=new BackgroundTasks(this);
		EasyTracker.getInstance().setContext(this);
		Intent data=getIntent();
		if(data.hasExtra("gold_tym"))
		{
			TextView wlc_text=(TextView)findViewById(R.id.wlc_text);
			gold_tym=data.getIntExtra("gold_tym", 6);
			wlc_text.setText(String.format(getResources().getString(R.string.msg_confirm_receive_birthday_gift), gold_tym));
		}
		Button ok=(Button)findViewById(R.id.ok);
		ok.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				EasyTracker.getTracker().sendEvent(Constants.EVENT, "Click receive TYM for birthday", "Click receive TYM for birthday", Long.valueOf(1));
				connectFacebook();
			}
		});
		Button cancel=(Button)findViewById(R.id.cancel);
		cancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				EasyTracker.getTracker().sendEvent(Constants.EVENT, "Cancel receive TYM for birthday", "Cancel receive TYM for birthday", Long.valueOf(1));
				finish();
			}
		});
		saveLastCheck();
	}
	public void saveLastCheck() {
		SharedPreferences shared=getPreferences(Activity.MODE_PRIVATE);
		SharedPreferences.Editor builder= shared.edit();
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String time = sdf.format(c.getTime());
		long unixCurrentTime = 0;
		try {
			unixCurrentTime = sdf.parse(time).getTime() / 1000L;
		} catch (ParseException ex) {
		}
		builder.putLong("last_check_birthday", unixCurrentTime);
		builder.commit();
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getTracker().sendView("Gift for birthday view");
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
//		try {
//			Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == FB_REQUEST_CODE && resultCode == RESULT_OK){
			
			Log.e("onActivityResult", "FB_REQUEST_CODE&RESULT_OK");
		} else if(requestCode == FB_REQUEST_CODE && resultCode == RESULT_CANCELED){
			Log.e("onActivityResult", "FB_REQUEST_CODE&RESULT_CANCELED");
		} else {
			try{
			fbLoginManager.loginSuccess(data);
			}catch(Exception ex)
			{
			}
			Log.e("onActivityResult", "loginSUccess");
		}
	}
	private void connectFacebook(){
		Log.e("ConnectFB","ConnectFB for sharing");
		String permissions[] = {"email", "read_stream","publish_stream", "read_friendlists"};
		FB_APP_ID = getResources().getString(R.string.fb_app_id);
		fbLoginManager = new FBLoginManager(this, R.layout.activity_login, FB_APP_ID, permissions);
		if(fbLoginManager.existsSavedFacebook()){
			fbLoginManager.loadFacebook();
		} else {
			fbLoginManager.login();
		}
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.e("onResume", "Here");
		EventBus.getDefault().register(this);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.e("onPause", "Here");
		EventBus.getDefault().unregister(this);

	}
	@Override
	public void loginSuccess(Facebook facebook) {
		// TODO Auto-generated method stub
		Log.e("loginFacebookSuccess","loginSuccess");
		final GraphApi graph = new GraphApi(facebook);
		progressDialog.setMessage(getResources().getString(R.string.sharing_on_facebook));
		progressDialog.setCancelable(false);
		progressDialog.show();
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				progressDialog.setCancelable(true);
			}
		}, 15000);
		new GetInfoSyn(graph).execute();
	}
	private class GetInfoSyn extends AsyncTask<Void, Void, Void>
	{
		private GraphApi graph;
		private User me=null;
		public GetInfoSyn(GraphApi graph)
		{
			this.graph=graph;
		}
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
				me = graph.getMyAccountInfo();
			} catch (EasyFacebookError e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			if(me!=null)
			{
				Log.e("getMyAccountInfo","getMyAccountInfo");
				fbAccount=me.getName();
			}else
			{
				fbAccount=getResources().getString(R.string.you);
			}
			AsyncExecutor.create().execute(new RunnableEx() {
				@Override
				public void run() throws Exception {
					// TODO Auto-generated method stub
					String postId;
					String description=String.format(getResources().getString(R.string.fb_msg_birthday_event), fbAccount,gold_tym);
					postId = graph.setStatus(description, null, null, null, null, "http://appstore.vn/app", null);
					EventBus.getDefault().post(new PostEvent(postId));
				}
			});
		}
		
	}
	private class SendConfirmAsyn extends AsyncTask<Void, Void, Void>
	{

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			HttpHelper.checkUserBirthday("confirm", Utils.getStaticAccessToken(BirthdayDialogActivity.this));
			return null;
		}	
	}
	public void onEventMainThread(PostEvent e){
		if(progressDialog.isShowing()){
			progressDialog.dismiss();
		}
		if(e.getPostId() != null){
			//start send request for checking
			new SendConfirmAsyn().execute();
		} else {
			Toast.makeText(this, R.string.share_fail, Toast.LENGTH_SHORT).show();
		}
	}
	@Override
	public void logoutSuccess() {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
//		super.onBackPressed();
	}
	@Override
	public void loginFail() {
		// TODO Auto-generated method stub
		if(progressDialog.isShowing())
		{
			progressDialog.dismiss();
		}
		Toast.makeText(this, getResources().getString(R.string.login_fb_fail), Toast.LENGTH_LONG).show();
	}
	private static class PostEvent {
		public String getPostId() {
			return postId;
		}

		String postId;

		public PostEvent(String postId) {
			this.postId = postId;
		}
	}
//	private static class PostGetInfoEvent
//	{
//		private String acc;
//
//		public String getAcc() {
//			return acc;
//		}
//
//		public void setAcc(String acc) {
//			this.acc = acc;
//		}
//		public PostGetInfoEvent(String acc)
//		{
//			this.acc=acc;
//		}
//	}
	public void onEventMainThread(CheckUserBirthdayFailed e){
		Log.e("OneventMainThread","CheckUserBirthdayFailed");
		SharedPreferences shared=getPreferences(Activity.MODE_PRIVATE);
		SharedPreferences.Editor builder= shared.edit();
		builder.putLong("last_check_birthday", 0L);
		builder.commit();
	}
	
	public void onEventMainThread(ConfirmUserBirthdaySucceed e){
		Log.e("OneventMainThread","ConfirmUserBirthdaySucceed");
		EasyTracker.getTracker().sendEvent(Constants.EVENT, "Get gift for birthday successfully", "Received gold tym for birthday", Long.valueOf(1));
		String msg=String.format(getResources().getString(R.string.msg_send_birthday_gift), gold_tym);
		showDialogMessage(msg);
	}
	public void onEventMainThread(ConfirmUserBirthdayFailed e){
		Log.e("OneventMainThread","ConfirmUserBirthdayFailed");
		boolean status=e.isStatus();
		if(!status)
		{
			showDialogMessage(getResources().getString(R.string.error_nega2));
		}else
		{
			showDialogMessage(getResources().getString(R.string.already_received_birthday_gift));
		}
		
	}
	public void showDialogMessage(String msg) {
		AlertDialog.Builder builder=new Builder(this);
		builder.setMessage(msg).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				String accessToken = Utils.getStaticAccessToken(BirthdayDialogActivity.this);
				if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
					bgTask.getUserInfo(accessToken);
				}
				finish();
			}
		});
		builder.show();
	}
}
